package com.ruoyi.api.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import com.deepoove.poi.data.MiniTableRenderData;
import com.deepoove.poi.data.PictureRenderData;
import com.deepoove.poi.data.RowRenderData;
import com.deepoove.poi.data.TextRenderData;
import com.deepoove.poi.policy.HackLoopTableRenderPolicy;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.system.domain.SpBmlist;
import com.ruoyi.system.domain.SpSaicheng;
import com.ruoyi.system.service.ISpBmlistService;
import com.ruoyi.system.service.ISpSaichengService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.SpDaibiao;
import com.ruoyi.system.service.ISpDaibiaoService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 代队Controller
 * 
 * @author ruoyi
 * @date 2022-11-11
 */
@RestController
@RequestMapping("/api/daibiao")
public class SpDaibiaoApiController extends BaseController
{
    @Autowired
    private ISpDaibiaoService spDaibiaoService;
    @Autowired
    private ISpSaichengService spSaichengService;
    @Autowired
    private ISpBmlistService spBmlistService;
    /**
     * 查询代队列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SpDaibiao spDaibiao)
    {
        startPage();
        List<SpDaibiao> list = spDaibiaoService.selectSpDaibiaoListWeb(spDaibiao);
        return getDataTable(list);
    }

    /**
     * 导出代队列表
     */
    @Log(title = "代队", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SpDaibiao spDaibiao)
    {
        List<SpDaibiao> list = spDaibiaoService.selectSpDaibiaoListWeb(spDaibiao);
        ExcelUtil<SpDaibiao> util = new ExcelUtil<SpDaibiao>(SpDaibiao.class);
        util.exportExcel(response, list, "代队数据");
    }


    @PostMapping("/exportword")
    public void exportword(HttpServletResponse response, SpDaibiao spDaibiao)
    {
        String basefilePath = RuoYiConfig.getUploadPath();
        List<SpDaibiao> list = spDaibiaoService.selectSpDaibiaoListWeb(spDaibiao);
        for(SpDaibiao daibiao:list){
            Map<String, Object> map = new HashMap<>();

            SpSaicheng sc = spSaichengService.selectSpSaichengByScId(daibiao.getScId());
            File folder = new File(basefilePath+"/"+sc.getScId()+"/");
            if(!folder.exists()){
                folder.mkdir();
            }
            File[] files = folder.listFiles();
            // 遍历并删除所有文件
            for (File file : files) {
                if (file.isFile()) {
                    file.delete();
                }
            }

            map.put("orgName",daibiao.getGname());
            map.put("scName",sc.getTitle());
            map.put("jieshao",daibiao.getGname());
            map.put("username",daibiao.getUsername());
            map.put("userdn",daibiao.getUserdn());
            map.put("jlname",daibiao.getJlname());
            map.put("jldn",daibiao.getJldn());

            String filePath = RuoYiConfig.getDownloadPath() + daibiao.getgPic();
            map.put("image", new PictureRenderData(540, 360, filePath));


            RowRenderData header = RowRenderData.build(
                    new TextRenderData("FFFFFF", "序号"),
                    new TextRenderData("FFFFFF", "姓名"),
                    new TextRenderData("FFFFFF", "性别"),
                    new TextRenderData("FFFFFF", "身份证"),
                    new TextRenderData("FFFFFF", "全国统一学籍号")
            );

            SpBmlist query  =  new SpBmlist();
            query.setDbId(daibiao.getDbId());
            List<SpBmlist> bmlist = spBmlistService.selectSpBmlistList(query);
            List<RowRenderData> list2 = new ArrayList<RowRenderData>();
            int inedex = 0;
            for(SpBmlist bp:bmlist){
                inedex = inedex+1;
                RowRenderData row = RowRenderData.build(
                        new TextRenderData("FFFFFF", inedex+""),
                        new TextRenderData("FFFFFF", bp.getSpName()),
                        new TextRenderData("FFFFFF", bp.getSex()),
                        new TextRenderData("FFFFFF", bp.getIdno()),
                        new TextRenderData("FFFFFF", bp.getUserCode())
                );
                list2.add(row);
            }


            map.put("table", new MiniTableRenderData(header,list2));
            ConfigureBuilder builder = Configure.newBuilder();
            HackLoopTableRenderPolicy policy = new HackLoopTableRenderPolicy();
            builder.bind("bianpaiList", policy);
            map.put("bianpaiList", bmlist);

            Configure configure = builder.build();
            XWPFTemplate template = XWPFTemplate.compile(basefilePath+"/tempword.docx", configure).render(map);
            try {
                FileOutputStream out = new FileOutputStream(basefilePath+"/"+sc.getScId()+"/"+sc.getTitle()+"报名表.docx");
                template.write(out);
                out.flush();
                out.close();
                template.close();
            } catch (IOException e) {
                e.printStackTrace();
            }



        }


//
//        ExcelUtil<SpDaibiao> util = new ExcelUtil<SpDaibiao>(SpDaibiao.class);
//        util.exportExcel(response, list, "代队数据");
    }

    /**
     * 获取代队详细信息
     */
    @GetMapping(value = "/{dbId}")
    public AjaxResult getInfo(@PathVariable("dbId") Long dbId)
    {
        return AjaxResult.success(spDaibiaoService.selectSpDaibiaoByDbId(dbId));
    }

    /**
     * 新增代队
     */
    @Log(title = "代队", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SpDaibiao spDaibiao)
    {
        return toAjax(spDaibiaoService.insertSpDaibiao(spDaibiao));
    }

    /**
     * 修改代队
     */
    @Log(title = "代队", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SpDaibiao spDaibiao)
    {
        return toAjax(spDaibiaoService.updateSpDaibiao(spDaibiao));
    }

    /**
     * 删除代队
     */
    @Log(title = "代队", businessType = BusinessType.DELETE)
	@DeleteMapping("/{dbIds}")
    public AjaxResult remove(@PathVariable Long[] dbIds)
    {
        return toAjax(spDaibiaoService.deleteSpDaibiaoByDbIds(dbIds));
    }
}
